package com.vanke.devops.api.controller.users;

import com.vanke.core.bean.ApiBaseResponse;
import com.vanke.core.exception.VankeBusinessException;
import com.vanke.core.exception.VankeCommonExCodeEnum;
import com.vanke.devops.api.base.BaseController;
import com.vanke.devops.api.controller.users.form.LoginForm;
import com.vanke.devops.domain.domain.users.ICaptchaDomainService;
import com.vanke.devops.domain.domain.users.IUsersService;
import com.vanke.devops.domain.domain.users.dto.UsersDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author 陈景阳
 * @since 2018/5/11
 */
@RestController
public class LoginController extends BaseController{

    @Autowired
    private ICaptchaDomainService captchaDomainService;

    @Autowired
    private IUsersService usersService;

    @PostMapping("/login")
    public ApiBaseResponse login(@Valid @RequestBody LoginForm form){
        UsersDTO usersDTO= usersService.login(form.getLoginName(),form.getPassword(),form.getCaptcha());
        return setResponse(usersDTO);
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response){
        //返回图形验证码
        BufferedImage buffImg = captchaDomainService.getCaptcha("login");
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        response.setContentType("image/png");
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos = null;
        try {
            sos = response.getOutputStream();
            ImageIO.write(buffImg, "png", sos);
            sos.close();
        } catch (IOException e) {
            throw new VankeBusinessException(VankeCommonExCodeEnum.SYS_TOO_BUSY);
        } finally {
            try {
                sos.close();
            } catch (IOException e) {
                throw new VankeBusinessException(VankeCommonExCodeEnum.SYS_TOO_BUSY);
            }
        }
    }
}
